package com.shenfc.fxzj.action.admin;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.shenfc.fxzj.constants.SuperAdminEnum;
import com.shenfc.fxzj.domain.MenuRootJson;
import com.shenfc.fxzj.domain.SysMenu;
import com.shenfc.fxzj.domain.SysUser;
import com.shenfc.fxzj.mapper.SysUserMapper;
import com.shenfc.fxzj.service.ISysMenuService;
import com.shenfc.fxzj.service.ISysUserService;
import com.shenfc.fxzj.util.HtmlUtil;
import com.shenfc.fxzj.util.TreeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

import static com.shenfc.fxzj.constants.CodeConstants.*;


@Controller
public class MainAdminAction extends BaseAction {

    private final static Logger logger = LoggerFactory.getLogger(MainAdminAction.class);

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @RequestMapping({"/index"})
    public String index() {
        return "admin/login";
    }

    @RequestMapping({"/adminLogin"})
    public String login() {
        return "admin/login";
    }

    @RequestMapping({"/adminToLogin"})
    public void toLogin(String username, String password, String verifyCode, String rememberMe, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();

        if (!(verifyCode.toUpperCase()).equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
            result.put(SUCCESS, false);
            result.put(MSG, "验证码错误！");
            HtmlUtil.writerJson(response, result);
            return;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe("on".equals(rememberMe));
        try {
            subject.login(token);

            SysUser sysUser = sysUserService.getSysUserByUserName(username);
            sysUser.setLoginCount(sysUser.getLoginCount()+1);
            subject.getSession().setAttribute(SESSION_USER, sysUser);

            sysUser.setLastLoginTime(new Date());
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
            result.put(SUCCESS, true);
        } catch (Exception e) {
            logger.error("登陆失败", e);
            result.put(SUCCESS, false);
            result.put(MSG, "用户名或密码错误！");
        }
        HtmlUtil.writerJson(response, result);
        //验证是否登录成功
//        if(currentUser.isAuthenticated()){
//            logger.info("用户[" + email + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
//            //把当前用户放入session
//            Session session = currentUser.getSession();
//            User tUser = permissionService.findByUserEmail(email);
//            session.setAttribute("currentUser",tUser);
//            return "/welcome";
//        }else{
//            token.clear();
//            return "redirect:login";
//        }
    }

    @RequestMapping({"/admin/main"})
    public ModelAndView main() {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SESSION_USER);
        List<SysMenu> sysMenuList;
        if (SuperAdminEnum.YES.getKey().equals(sysUser.getSuperAdmin())) {
            sysMenuList = sysMenuService.getAllSysMenus();
        } else {
            sysMenuList = sysMenuService.getSysMenusByUserId(sysUser.getId());
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", sysUser);

        TreeUtil util = new TreeUtil(sysMenuList);
        modelAndView.addObject("menuList", util.getRootNodes());
        modelAndView.setViewName("admin/index");
        return modelAndView;
    }

    @RequestMapping({"/admin/getMenu"})
    public void getMenu(HttpServletResponse response) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SESSION_USER);
        List<SysMenu> sysMenuList;
        if (SuperAdminEnum.YES.getKey().equals(sysUser.getSuperAdmin())) {
            sysMenuList = sysMenuService.getAllSysMenus();
        } else {
            sysMenuList = sysMenuService.getSysMenusByUserId(sysUser.getId());
        }

        TreeUtil util = new TreeUtil(sysMenuList);
        MenuRootJson menuRootJson=new MenuRootJson();
        menuRootJson.setContentManagement(util.getLayUiMenus());
        HtmlUtil.writerJson(response,menuRootJson);
    }

    @RequestMapping({"/adminLogout"})
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/adminLogin";
    }
}